package club.qweqwe.dao;

import club.qweqwe.dao.impl.BasicDaoImpl;
import club.qweqwe.model.dbobj.User;
import club.qweqwe.model.form.Register;
import club.qweqwe.utils.ReflectUtils;

import javax.sql.DataSource;
import java.util.UUID;

public class UserDaoImpl extends BasicDaoImpl<User> {
    public UserDaoImpl() {
    }

    public UserDaoImpl(DataSource dataSource) {
        super(dataSource);
    }

    public boolean insert(User user){
        String tableName = getTypeName();
        String sql = String.format("INSERT INTO %s (id, account, password) VALUE(?, ?, ?);", tableName);
        int result = insert(sql, user.getId(), user.getAccount(), user.getPassword());
        return result > 0;
    }

    /**
     *
     * @param register
     * @return 返回注册成功的用户UUID，出错则为null
     */
    public User register(Register register){
        UUID uuid = UUID.randomUUID();
        User user = new User();
        user.setId(uuid.toString());
        user.setAccount(register.getAccount());
        user.setPassword(register.getPassword());

        return insert(user) ? user : null;
    }


    public User query(String account, String password){
        String tableName = ReflectUtils.getClassName(ReflectUtils.getSuperGenericType(getClass()));
        String sql = String.format("SELECT * FROM %s WHERE account = ? AND password = ?;", tableName);
        return query(sql, account, password);
    }

}
